// 1、数组扁平化
// a、递归
function flatten(arr) {
    var res = [];
    for (let i = 0, len = arr.length; i < len; i++) {
        if (Array.isArray(arr[i])) {
            res = res.concat(flatten(arr[i]));
        } else {
            res.push(arr[i]);
        }
    }
    return res;
}

// b、ES6 实现
function flatten1(arr) {
    while (arr.some(item => Array.isArray(item))) {
        arr = [].concat(...arr);
    }
    return arr;
}
// console.log();
// console.log(flatten1([2, 1, 5, [2, [1, 9, 3]], 4]));
// console.log([...new Set(flatten1([2, 1, 5, [2, [1, 9, 3]], 4]))]);

// 2、扁平化N层
// 扁平两层
function flatten2(arr, n){
    let res = [];
    arr.forEach(item => {
        res = res.concat(item);
    });
    return res;
}


// 扁平化N层
let n = 3
let max = 0
function flattenN1(arr) {
    max++;
    var res = [];
    for (let i = 0, len = arr.length; i < len; i++) {
        if (Array.isArray(arr[i]) && max<=3) {
            console.log(" max",max);
            max++;
            res = res.concat(flattenN1(arr[i]));
        } else {
            res.push(arr[i]);
        }
    }
    return res;
}
console.log("flattenN", flattenN1([2, [1,  [2, [1, 9, 3]], 4]], 2));

let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];

// 3、数组打乱
// sort排序法
// arr.sort(() => Math.random() - 0.5);
// console.log(arr);

function shuffle(arr) {
    let i = arr.length;
    while (i) {
        let j = Math.floor(Math.random() * i--);
        [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
}

console.log(shuffle(arr));

// 4、旋转数组
// 输入: [1,2,3,4,5,6,7] 和 k = 3
// 输出: [5,6,7,1,2,3,4]
// 解释:
// 向右旋转 1 步: [7,1,2,3,4,5,6]
// 向右旋转 2 步: [6,7,1,2,3,4,5]
// 向右旋转 3 步: [5,6,7,1,2,3,4]
const rotate = function (nums, k) {
  const l = nums.length;
  k = k % l;
  for (let i = 0; i < k; i++) {
    nums.unshift(nums.pop());
  }
};
let nums = [1,2,3,4,5,6,7];
rotate(nums, 3);
console.log("nums:", nums);

// 5、数组切割
function splitArray(arr, size) {
    let res = [];
    for (let i = 0; i < arr.length;) {
        res.push(arr.slice(i, i + size));
        i = i + size;
    }
    return res;
}
let data = [1, 2, 3, 4, 5, 6];
let res = splitArray(data, 4);
console.log(res);
